package org.zjframework.traceframe.common.MessageConverter;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.zjframework.traceframe.common.util.aes.AES;
import org.zjframework.traceframe.common.util.aes.AESUtil;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Created by John on 2017/6/8.
 */
public class FreeWorkMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {


//    @Override
//    protected void writeInternal(Object object,
//                                 HttpOutputMessage outputMessage) throws IOException,
//            HttpMessageNotWritableException {
//
//        //使用Jackson的ObjectMapper将Java对象转换成Json String
//        ObjectMapper mapper = new ObjectMapper();
//        String json = mapper.writeValueAsString(object);
//        //加密
//        String result = json + "加密了！";
//        //输出
//        outputMessage.getBody().write(result.getBytes());
//    }

//    @Override
//    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
//        //IOUtils.toString(inputMessage.getBody());
//        //解密
//        String json = AESUtil.decrypt(inputMessage.getBody());
//        JavaType javaType = getJavaType(clazz, null);
//        //转换
//        return this.objectMapper.readValue(json, javaType);
//    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //使用Jackson的ObjectMapper将Java对象转换成Json String
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(object);
        //加密
        String result = AESUtil.encrypt(json);
        //输出
        outputMessage.getBody().write(result.getBytes());
    }

//    @Override
//    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
//        JavaType javaType = this.getJavaType(clazz, (Class)null);
//        //return this.readJavaType(javaType, inputMessage);
//        return super.readInternal(clazz, inputMessage);
//    }

}
